package com.ctakit.kiwi.web.view.resolver;

import com.ctakit.kiwi.web.util.ThreadLocalUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import java.util.Locale;
import java.util.Map;

/**
 * <b>function:</b>
 *
 * @author lizhenmin
 * @version 1.0
 * @createDate 2011 Jul 25, 2011 11:21:37 AM
 * @email andyhome108@163.com
 */
public class MultipleViewResolver implements ViewResolver {
    //private static String JSON = "json";
    //private static String XML = "xml";
    /**
     * 视图解析器相对应的 map,key为返回字符串的前缀, 台 jsp:login 则对应key 为jsp 的视图
     */
    private Map<String, ViewResolver> resolvers;
    private String defaultViewResolverName = null;// 默认的视图解析器名称

    public void setDefaultViewResolverName(String defaultViewResolverName) {
        this.defaultViewResolverName = defaultViewResolverName;
    }

    public String getDefaultViewResolverName() {
        return defaultViewResolverName;
    }

    public void setResolvers(Map<String, ViewResolver> resolvers) {
        this.resolvers = resolvers;
    }

    /**
     * 根据视图的前缀名返回不同的视图 如: jsp:login 返回key为jsp视图
     */
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        ViewResolver resolver = null;
        String resolverName = null;// 视图解析器名称

        String ext = ThreadLocalUtils.getUriExt();
        resolver = resolvers.get(ext);
        if (resolver != null) {
            return resolver.resolveViewName(viewName, locale);
        }
        int resolverNameIndex = viewName.indexOf(":");
        if (resolverNameIndex == (-1)) {
            resolver = resolvers.get(viewName);
            if (resolver == null) {
                resolver = getDefaultView();
            }
        } else {
            // 视图解析器名称:
            resolverName = viewName.substring(0, resolverNameIndex);
            if ("redirect".equals(resolverName) || "forward".equals(resolverName)) {
                resolver = getDefaultView();
            } else {
                // 取出对应的ViewResolver:
                resolver = resolvers.get(resolverName);
                // 视图名称
                viewName = viewName.substring(resolverNameIndex + 1);
            }
        }
        if (resolver != null) {

            return resolver.resolveViewName(viewName, locale);
        }
        // 没有找到对应的ViewResolver就抛异常:
        return null;

    }

    private ViewResolver getDefaultView() {
        return resolvers.get(defaultViewResolverName); // 默认的视图解析器
    }

}
